/*
 * Copyright (c) 2018.
 * This file was written by Fancyears·Milos·Malvis @connor. Any question/bug you can't post to 1243093366@qq.com.
 * ALL RIGHTS RESERVED.
 */
package org.fancyears.sql;

import java.io.IOException;
import java.io.Reader;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @author: Fancyears·Milos·Malvis
 * @CreateDate: 2018年12月7日 上午10:22:02
 * @Description: session工厂，一般化设置
 */
public class FactoryManager {
	private static Reader reader = null;
	private static SqlSessionFactory factory = null;
	/**
	 * where the configuration file path
	 */
	public static String resource = "mybatis-config";
	public static String env = "-dev";
	public static String end = ".xml";
	private final static Object lock = new Object();
	static {
		try {
			Properties properties = new Properties();
			Reader reader = Resources.getResourceAsReader("application.properties");
			properties.load(reader);
			env = properties.getProperty("active-file");
			if (null == env || env.length() <= 0) {
				env = "";
			}
			if (!env.contains("-")) {
				env = "-" + env;
			}
			reader = Resources.getResourceAsReader(resource + env + end);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			factory = builder.build(reader);
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("没有找到配置文件" + (resource + env + end)
					+ "，请确保项目根目录下有application.properties文件，并确保有active-file属性所指向的mybatis配置文件");
		}

	}

	/**
	 * DefaultSqlSessionFactory 是一个重型对象
	 * 
	 * @return
	 * @throws RuntimeException
	 */
	public static SqlSessionFactory getInstance() throws RuntimeException {
		if (factory == null) {
			synchronized (lock) {
				if (factory == null)
					try {
						reader = Resources.getResourceAsReader(resource + env + end);
						SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
						factory = builder.build(reader);
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
						throw new RuntimeException("没有找到配置文件" + (resource + env + end)
								+ "，请确保项目根目录下有application.properties文件，并确保有active-file属性所指向的mybatis配置文件");
					}
			}
		}
		return factory;
	}

	public static SqlSession getSession() throws RuntimeException {
		return getInstance().openSession();
	}
}
